import { Context } from 'egg';

// 自定义的中间件：验证token
export default function jwtAuth(options: any): any {
  return async (ctx: Context, next: () => Promise<any>) => {
    const token = ctx.request.header.authorization;
    let decode: any = '';
    if (token) {
      try {
        // 解码token
        decode = await ctx.app.jwt.verify(token, options.secret);
        ctx.authUser = decode.username;
        console.log('decode======>', decode);
        await next();
      } catch (error) {
        ctx.status = 401;
        ctx.body = {
          message: error.message,
        };
        return;
      }
    } else {
      ctx.status = 401;
      ctx.body = {
        message: '没有token',
      };
      return;
    }
  };
}
